# coding: utf-8
import hashlib
import os
import random
from functools import wraps

import web
from web.contrib.template import render_jinja
from web.db import MySQLDB

db: MySQLDB = web.database(dbn='mysql', host='192.168.20.216', user='root', pw='123456', db='db_news')

project_root = os.path.dirname(os.path.dirname(__file__))
templates_path = os.path.join(project_root, 'templates')


def render(temp_path, *args, **kwargs):
    path_split = temp_path.rsplit('/', 1)
    if len(path_split) == 2:
        sub_path, file_name = path_split
    else:
        sub_path, file_name = '', path_split[0]

    _render = render_jinja(
        [templates_path, os.path.join(templates_path, sub_path)],
        encoding = 'utf-8'
    )

    return getattr(_render, file_name)(*args, **kwargs)


def sha1(str_):
    if not isinstance(str_, str):
        str_ = str(str_)
    return hashlib.sha1(str_.encode()).hexdigest()


def show_error(txt):
    return render('msg', txt=txt)


def show_success(txt, url=''):
    web.header('Content-Type', 'text/html; charset=utf-8')
    return f"""
    <script>
    alert('{txt}');
    window.location.href = '{url}';
    </script>
    """


def require_captcha(func):
    def wrapper(*args, **kwargs):
        post = web.input()
        post_captcha = post.captcha

        session_captcha = web.ctx.session['captcha']
        web.ctx.session['captcha'] = str(random.randint(10000000, 99999999))

        if post_captcha.lower() != session_captcha.lower():
            return show_error('验证码错误')

        return func(*args, **kwargs)

    return wrapper


def generate_random_str(length):
    char_list = [chr(i) for i in range(97, 123)] + list(range(10))
    random_list = random.sample(char_list, length)
    random_list = [str(i) for i in random_list]

    return ''.join(random_list)


def format_time1(_datetime):
    return _datetime.strftime("%Y-%m-%d %H:%M:%S")


def get_user_id():
    try:
        user_id = int(web.ctx.session['user_id'])
    except Exception as e:
        user_id = 0

    return user_id


def get_current_user():
    user_id = get_user_id()

    return get_user(user_id)


def get_user(user_id):

    if not user_id:
        return None

    try:
        user = db.select('user', where={'id': user_id})[0]
    except Exception as e:
        user = None

    return user


def set_self_user(func):
    def wrapper(self, *args, **kwargs):
        self.user = get_current_user()

        return func(self, *args, **kwargs)

    return wrapper


def real_path(*path):
    root_path = os.path.dirname(os.path.dirname(__file__))
    real_file_path = os.path.join(root_path, *path)

    return real_file_path


def safe_html(txt):
    return txt.replace('<', '&lt;').replace('>', '&gt;').replace('\n', '<br>').replace(' ', '&nbsp;')
